import type * as QianKun from 'qiankun';
import { RouteRecordName } from 'vue-router';
import _ from 'lodash';
import Session from '@core/engine/Session';
import IconEShield from '@main/assets/eshield.svg';
import IconFirewall from '@main/assets/firewall.svg';
import IconEmptyShield from '@main/assets/empty-shield.svg';
import subApps, { AppNames, SubApp, subAppViewportId } from '@/subApps';
import HistoryHelper from '@/src/utils/HistoryHelper';
import EnvConfig from '@/src/utils/EnvConfig';
import router from './router';

export default class SubAppHelper {
  static _availableApps: Array<SubApp>;

  static iconMap = {
    [AppNames.EShield]: IconEShield,
    [AppNames.Firewall]: IconFirewall,
  };

  static refreshAvailableApps = () => {
    const availableSubApps = Session.getAvailableSubApps();
    SubAppHelper._availableApps = subApps.filter((app) => availableSubApps.includes(app.name));
  };

  static getAvailableList = () => {
    if (!SubAppHelper._availableApps) {
      SubAppHelper.refreshAvailableApps();
    }
    return SubAppHelper._availableApps;
  };

  static getListForMenu = () => {
    const availableList = SubAppHelper.getAvailableList();
    return availableList
      .filter((app) => app.isShowInMenu !== false)
      .map((app) => ({ ...app, icon: SubAppHelper.getIconOfOne(app) }));
  };

  static getListForHomePage = () => {
    const availableList = SubAppHelper.getAvailableList();
    return _.groupBy(
      availableList
        .filter((app) => app.productGroup !== undefined)
        .map((app) => ({ ...app, icon: SubAppHelper.getIconOfOne(app) })),
      'productGroup',
    );
  };

  static getIconOfOne = (app: SubApp) => {
    return SubAppHelper.iconMap[app.name] || IconEmptyShield;
  };

  static getListForQianKun = () => {
    const availableList = SubAppHelper.getAvailableList();
    return availableList.map((app) => SubAppHelper.buildQianKunConfigOfOne(app));
  };

  static buildQianKunConfigOfOne = (app: SubApp): QianKun.RegistrableApp<QianKun.ObjectType> => {
    const { name, localPort } = app;
    return {
      name,
      entry: EnvConfig.isNodeEnvDevelopment() ? `//localhost:${localPort}` : `/subApps/${name}/`,
      container: `#${subAppViewportId}`,
      activeRule: HistoryHelper.getSubAppPath(app.name),
    };
  };

  static getCurrentSubApp = (routeName?: RouteRecordName | null): string | undefined => {
    const availableSubAppNames = SubAppHelper.getAvailableList().map((subApp) => subApp.name);
    const currentRouteName = routeName || router.currentRoute.value.name;
    if (currentRouteName && availableSubAppNames.includes(currentRouteName?.toString())) {
      return currentRouteName?.toString();
    }
    return undefined;
  };
}
